#include "udialogwidget.h"
#include "utexteditwidget.h"
#include "umessage.h"
#include <QDateTime>  
#include <QJsonArray>
UDialogWidget::UDialogWidget(QWidget *parent)
	: QWidget(parent)
{
	setAttribute(Qt::WA_StyledBackground, true);//默认Qwidget类 无法设置颜色
	setAttribute(Qt::WA_TranslucentBackground);
	setFixedSize(850,460);
	setStyleSheet(R"(UDialogWidget{background-color:#808080;border:none;})");
	connect(UClientServer::Instance(), &UClientServer::alreadyRead, this, &UDialogWidget::readResponse); //获取服务器发送的信息
}

void UDialogWidget::readResponse(const OPERATOR type, QByteArray datagram)
{
	switch (type)
	{
	case OPERATOR::SAMEINFO:     ParseReturnInfo(datagram);         break;
	case OPERATOR::JSONINFO:     ParseReturnJson(datagram);         break;
	case OPERATOR::UPDATEINFO:   ParseUpdateJson(datagram);			break;
	case OPERATOR::ADDBOOK:      ParseAddBook(datagram);			break;
	case OPERATOR::REVISEBOOK:   ParseReviseBook(datagram);			break;
	case OPERATOR::UNKNINFO:     qDebug() << "识别失败";		        break;
	}
}

void UDialogWidget::ParseReviseBook(const QByteArray& datagram)
{
	QDataStream ds(datagram);
	OPERATOR buffer;
	QByteArray data;
	ds >> buffer >> data;
	displayMessage(QString(data), false);
}

void UDialogWidget::ParseQueryBook(const QByteArray& datagram)
{
	QDataStream ds(datagram);
	OPERATOR buffer;
	QByteArray data;
	ds >> buffer >> data;
	displayMessage(QString(data), false);
}

void UDialogWidget::ParseAddBook(const QByteArray& datagram)
{
	QDataStream ds(datagram);
	OPERATOR buffer;
	QByteArray data;
	ds >> buffer >> data;
	displayMessage(QString(data), false);
}

void UDialogWidget::ParseReturnJson(const QByteArray& datagram)
{
	displayMessage(datagram.mid(4).data(), false);
}

void UDialogWidget::ParseUpdateJson(const QByteArray& datagram)
{
	QDataStream ds(datagram);
	OPERATOR buffer;
	QString text;
	ds >> buffer >> text;
	displayMessage(text, false);
}

void UDialogWidget::ParseReturnInfo(const QByteArray& datagram)
{
	QDataStream ds(datagram);
	OPERATOR buffer;
	QString text;
	ds >> buffer >> text;
	displayMessage(text, false);
}

UDialogWidget::~UDialogWidget()
{}

void UDialogWidget::displayMessage(const QString& text, bool isSelf)
{
	m_pMessageList.push_back(new UMessage(this, text, QDateTime::currentDateTime().toString("HH:mm:ss"), isSelf));
	update();
}

void UDialogWidget::paintEvent(QPaintEvent* event)
{
	int height = 0;
	for (auto message = m_pMessageList.rbegin(); message != m_pMessageList.rend(); ++message)
	{
		if((*message)->m_isSelf == true)
			(*message)->move(845- (*message)->width(), height+5);
		else
			(*message)->move(5, height+5);
		height += (*message)->height() + 5;
		(*message)->raise();
		(*message)->show();
	}
}